<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-lock /></el-icon>
            <div class="stat-info">
              <div class="stat-title">权限总数</div>
              <div class="stat-value">{{ permissions.length }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">用户相关</div>
              <div class="stat-value">{{permissions.filter(p => p.name.includes('用户')).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">角色相关</div>
              <div class="stat-value">{{permissions.filter(p => p.name.includes('角色')).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider content-position="left">权限列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-lock /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">权限管理</span>
    </div>
    <div class="toolbar">
      <el-input v-model="permSearch" placeholder="请输入权限名称/描述" style="width: 240px; margin-right: 16px;" clearable />
      <el-button type="primary" @click="handlePermSearch">搜索</el-button>
      <el-button type="success" @click="openAddPermDialog" style="margin-left: 16px;">添加权限</el-button>
    </div>
    <el-table :data="pagedPerms" style="width: 100%;">
      <el-table-column prop="name" label="权限名称" />
      <el-table-column prop="desc" label="描述" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="openEditPermDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeletePerm(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="filteredPerms.length" :page-size="permPageSize" :current-page="permCurrentPage" @current-change="handlePermPageChange" style="margin-top: 16px; text-align: right;" />
    
    <el-dialog :title="permDialogMode === 'add' ? '添加权限' : '编辑权限'" v-model="permDialogVisible" width="400px" @close="resetPermDialog">
      <el-form :model="permDialogForm" :rules="permDialogRules" ref="permDialogFormRef" label-width="80px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permDialogForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="permDialogForm.desc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPermDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 权限管理数据
const permissions = ref([])

// 获取权限数据（对接后端）
async function fetchPermissions() {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get(getApiUrl('/permission/list'), {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (res.data && Array.isArray(res.data)) {
      permissions.value = res.data.map(permission => ({
        id: permission.id,
        name: permission.name,
        desc: permission.description || ''
      }))
    } else {
      permissions.value = []
    }
    console.log('获取到的权限数据:', permissions.value)
  } catch (e) {
    console.error('获取权限失败:', e)
    ElMessage.error('获取权限失败: ' + (e.response?.data || e.message))
    permissions.value = []
  }
}

// 创建权限
async function createPermission(permissionData) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.post(getApiUrl('/permission/create'), {
      code: permissionData.name.toLowerCase().replace(/\s+/g, '_'),
      name: permissionData.name,
      description: permissionData.desc
    }, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('添加成功')
      return true
    }
  } catch (e) {
    console.error('创建权限失败:', e)
    ElMessage.error('创建权限失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 更新权限
async function updatePermission(permissionData) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.put(getApiUrl(`/permission/update/${permissionData.id}`), {
      name: permissionData.name,
      description: permissionData.desc
    }, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('编辑成功')
      return true
    }
  } catch (e) {
    console.error('更新权限失败:', e)
    ElMessage.error('更新权限失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 删除权限
async function deletePermission(permissionId) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.delete(getApiUrl(`/permission/delete/${permissionId}`), {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('删除成功')
      return true
    }
  } catch (e) {
    console.error('删除权限失败:', e)
    ElMessage.error('删除权限失败: ' + (e.response?.data || e.message))
    return false
  }
}

const permSearch = ref('')
const permSearchKeyword = ref('')
const permPageSize = ref(10)
const permCurrentPage = ref(1)
const permDialogVisible = ref(false)
const permDialogMode = ref('add')
const permDialogForm = ref({ id: null, name: '', desc: '' })
const permDialogFormRef = ref(null)
const permDialogRules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

const filteredPerms = computed(() => {
  if (!permSearchKeyword.value) return permissions.value
  return permissions.value.filter(p =>
    p.name.includes(permSearchKeyword.value) ||
    p.desc.includes(permSearchKeyword.value)
  )
})

const pagedPerms = computed(() => {
  const start = (permCurrentPage.value - 1) * permPageSize.value
  return filteredPerms.value.slice(start, start + permPageSize.value)
})

function handlePermSearch() {
  permSearchKeyword.value = permSearch.value
  permCurrentPage.value = 1
}

function openAddPermDialog() {
  permDialogMode.value = 'add'
  Object.assign(permDialogForm.value, { id: null, name: '', desc: '' })
  permDialogVisible.value = true
  nextTick(() => permDialogFormRef.value && permDialogFormRef.value.clearValidate())
}

function openEditPermDialog(row) {
  permDialogMode.value = 'edit'
  Object.assign(permDialogForm.value, row)
  permDialogVisible.value = true
  nextTick(() => permDialogFormRef.value && permDialogFormRef.value.clearValidate())
}

function resetPermDialog() {
  Object.assign(permDialogForm.value, { id: null, name: '', desc: '' })
}

async function submitPermDialog() {
  permDialogFormRef.value.validate(async valid => {
    if (!valid) return
    
    try {
      let success = false
      
      if (permDialogMode.value === 'add') {
        success = await createPermission(permDialogForm.value)
      } else {
        success = await updatePermission(permDialogForm.value)
      }
      
      if (success) {
        permDialogVisible.value = false
        await fetchPermissions()
      }
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

async function handleDeletePerm(row) {
  try {
    await ElMessageBox.confirm(`确定要删除权限 ${row.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const success = await deletePermission(row.id)
    if (success) {
      await fetchPermissions()
      nextTick(() => {
        if (pagedPerms.value.length === 0 && permCurrentPage.value > 1) {
          permCurrentPage.value--
        }
      })
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

function handlePermPageChange(page) {
  permCurrentPage.value = page
}

onMounted(() => {
  fetchPermissions()
})
</script>

<style scoped>
/* 系统管理内容区美化 */
.sys-section-bg {
  background: linear-gradient(135deg, #f8fafc 0%, #e6ecf5 100%);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 64, 255, 0.06);
  padding: 32px 32px 24px 32px;
  margin-bottom: 24px;
  min-height: 600px;
  max-width: 1400px;
  width: 92vw;
  margin-left: auto;
  margin-right: auto;
}

/* 统计行和卡片样式 */
.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

/* 统计卡片样式 */
.stat-card {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 4px 0;
}
</style> 